package de.tum.beilmeiner.im.server.dao.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;

import de.novanic.eventservice.client.event.domain.DomainFactory;
import de.tum.beilmeiner.im.server.dao.ChatRoomDao;
import de.tum.beilmeiner.im.shared.model.ChatRoom;
import de.tum.beilmeiner.im.shared.model.UUID;
import de.tum.beilmeiner.im.shared.model.User;

public class ChatRoomDaoImpl implements ChatRoomDao {

	private static final ChatRoomDaoImpl INSTANCE = new ChatRoomDaoImpl();
	private LinkedList<ChatRoom> allRooms = null;

	public static ChatRoomDaoImpl getInstance() {
		return INSTANCE;
	}

	
	private ChatRoomDaoImpl() {
		allRooms = new LinkedList<ChatRoom>();
	}

	@Override
	public void addChatRoom(ChatRoom room) {
		allRooms.add(room);

	}

	@Override
	public void removeChatRoom(ChatRoom room) {
		allRooms.remove(room.getRoomId());

	}

	@Override
	public LinkedList<ChatRoom> getAllChatRooms() {
		return allRooms;
	}

	@Override
	public void addUsertoChatRoom(User user, ChatRoom room) {
		room.addUser(user);

	}

	@Override
	public void removeUserfromChatRoom(User user, ChatRoom room) {
		room.getUsersInRoom().remove(user.getUserId());
	}


	public ChatRoom createChatRoom(User user1, User user2) {

		for (ChatRoom room : allRooms) {
			HashMap<String, User> usersInRoom = room.getUsersInRoom();

			if (room.getUsersInRoom().containsKey(user1.getUserId()) && room.getUsersInRoom().containsKey(user2.getUserId())) {

				return room;
			}

		}
		// if we havent found any chatroom with these two users we have to
		ChatRoom newroom = new ChatRoom(DomainFactory.getDomain(UUID.uuid(15)), user1);
		newroom.addUser(user1);
		newroom.addUser(user2);
		allRooms.add(newroom);
		return newroom;

	}

	public void removeUserfromAllChatRooms(User logoutUser) {

		for (ChatRoom room : allRooms) {
			if (room.getUsersInRoom().containsKey(logoutUser)) {
				removeUserfromChatRoom(logoutUser, room);
			}
		}

	}

}
